package com.nsn.das.midas.rest;

import javax.annotation.Resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.codehaus.jettison.json.JSONArray;
import org.springframework.stereotype.Component;

import com.nsn.das.midas.service.MMLClassManager;
import com.nsn.das.midas.service.assembler.CommandClassAssembler;

@Component
@Path("/commandClass")
public class CommandClassRestService {
	@Resource(name="mmlClassManager")
	private MMLClassManager mmlClassManager;
	
	@Resource(name="commandClassAssembler")
	private CommandClassAssembler commandClassAssembler;
	
	
	@POST
	@Path("/save")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response saveCommandClassData(JSONArray array){
		try {
			mmlClassManager.saveMMLClass(commandClassAssembler.retriveClassDataFromJson(array));
		} catch (Exception e) {
			 Response.status(404).build();
		}
		
		return Response.status(200).build();
	}
	
	@GET
	@Path("/list/{pageIndex}/{pageSize}")
	public Response getCommandClassByPage(@PathParam("pageIndex") int pageIndex,@PathParam("pageSize") int pageSize){
		JSONArray result = commandClassAssembler.buildClassDataListJson(pageIndex,pageSize);
		return Response.status(200).entity(result).build();
	}
	
	@GET
	@Path("/{id}")
	public Response getCommandClassById(@PathParam("id") long id){
		try {
			return Response.status(200)
					.entity(commandClassAssembler.buildClassDataJson(id))
					.build();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Response.status(500).build();
	}
	
	@GET
	@Path("/availableLetters")
	public Response getAvailableLetters(){
		try {
			return Response.status(200)
					.entity(commandClassAssembler.buildAvailableLetterJson())
					.build();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Response.status(500).build();
	}
}
